﻿using Luna小店.原型;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Debug;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WorkFlowConsoleApp;
using WorkflowCore.Interface;

namespace Luna小店.service.workflow
{
    public class WorkflowService
    {

        IServiceProvider serviceProvider = null;
        bool serviceStarted = false;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="taskDTO"></param>
        public void StartWorkFlow(TaskDTO taskDTO)
        {
            // Demo1:Hello World
            if (serviceProvider == null)
            {
                this.serviceProvider = this.ConfigureServices();
            }

            var host = this.serviceProvider.GetService<IWorkflowHost>();
            host.RegisterWorkflow<TaskWorkflow, TaskDTO>();

            // 如果host启动了，不能再次启动，但没有判断方法
            if (!serviceStarted)
            {
                host.Start();
                this.serviceStarted = true;
            }

            host.StartWorkflow("打样", 1, taskDTO);
        }

        public void StopWorkflow()
        {
            try
            {
                var host = this.serviceProvider.GetService<IWorkflowHost>();
                host.Stop();
            }
            catch { }

            this.serviceStarted = false;
        }

        /// <summary>
        /// 配置workflow
        /// </summary>
        /// <returns></returns>
        private IServiceProvider ConfigureServices()
        {
            //setup dependency injection
            IServiceCollection services = new ServiceCollection();
            services.AddLogging();
            services.AddWorkflow();
            //services.AddWorkflow(x => x.UseMySQL(@"server=rm-8vb733a3r2o1oxjsjno.mysql.zhangbei.rds.aliyuncs.com;port=3306;user id=root;password=Win2003@;database=workflow;charset=utf8", true, true));
            //services.AddWorkflow(cfg =>
            //{
            //    cfg.UseRedisPersistence("192.168.5.239:6379", "sample4");
            //    cfg.UseRedisLocking("192.168.5.239:6379");
            //    cfg.UseRedisQueues("192.168.5.239:6379", "sample4");
            //    cfg.UseRedisEventHub("192.168.5.239:6379", "channel1");
            //});

            // 这些个构造函数带参数的，需要添加到transient中
            //services.AddTransient<HelloWorld>();
            //services.AddTransient<GoodbyeWorld>();
            //services.AddTransient<SleepStep>();

            var serviceProvider = services.BuildServiceProvider();

            //config logging
            var loggerFactory = serviceProvider.GetService<ILoggerFactory>();
            loggerFactory.AddProvider(new DebugLoggerProvider());

            return serviceProvider;
        }
    }
}
